//
//  WmcWebViewVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/5/9.
//

import UIKit
import WebKit

// MARK: - 扩展WmcWebVC + WmcNavigatorProtocol

extension WmcWebVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return navPaths
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        return makeNavgationVC(parms: parms)
    }
}

// MARK: - 扩展WmcWebVC + WmcVMProtocol

extension WmcWebVC: WmcVMProtocol {
    typealias VMType = WmcWebVM
}

extension WmcWebVC {
    
    enum JSMessage: String {
        /// 联系我们
        case sign_contact_us
    }
}

// MARK: - [WmcWebVC]

class WmcWebVC: WmcBaseVC {
    
    /// 路由path
    class var navPaths: [WmcNavigatorManager.Path] {
        return [.web]
    }
    
    /// JS原生交互对象
    private(set) lazy var scriptHandler: WmcScriptHandler = {
        let handler = WmcScriptHandler(webView: webView)
        return handler
    }()
    
    // Lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        registerHandlers()
        if let urlString = viewModel.urlString,
           let url = URL(string: urlString)
        {
            let req = URLRequest(url: url)
            webView.load(req)
        }
        
    }
    
    deinit {
        scriptHandler.clearMessageHandlers()
    }

    // Internal

    lazy var webView: WKWebView = {
        let webView = WKWebView()
        webView.uiDelegate = self
        return webView
    }()

    override func makeUI() {
        makeNavView()

        addSubview(webView)
        webView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }
    
    override func backAction() {
        let count = navigationController?.viewControllers.count ?? 0
        if count >= 2 {
            popVC()
        } else {
            dismissVC()
        }
    }
    
    /// 注册JS调用原生方法
    func registerHandlers() {
        scriptHandler.register(method: "ypNative") {
            [weak self] params in
            guard let messageId = params["messageId"] as? String,
                  let message = JSMessage(rawValue: messageId) else {
                print("未知JS方法")
                return
            }
            guard let self = self else { return }
            self.handleJSMessage(message, params: params)
        }
    }
    
    /// 处理JS调用原生
    /// - Parameters:
    ///   - message: 方法名
    ///   - params: 参数
    func handleJSMessage(_ message: JSMessage, params: [String: Any]) {}
    
    /// 构造路由控制器
    class func makeNavgationVC(parms: WmcNavigatorManager.Parms) -> UIViewController {
        var vm = WmcWebVM()
        if let viewModel = parms.context as? WmcWebVM {
            vm = viewModel
        }
        let vc = WmcWebVC(vm)
        vc.modalPresentationStyle = vm.modalPresentationStyle
        return vc
    }
}

extension WmcWebVC: WKUIDelegate {
    
    /// 显示h5的alert弹窗
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        let vc = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
        vc.addAction(UIAlertAction(title: "确定", style: .default, handler: { _ in
            completionHandler()
        }))
        present(vc, animated: true, completion: nil)
    }
    
    /// 显示h5的confirm弹窗
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        let vc = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
        vc.addAction(UIAlertAction(title: "取消", style: .default, handler: { _ in
            completionHandler(false)
        }))
        vc.addAction(UIAlertAction(title: "确定", style: .default, handler: { _ in
            completionHandler(true)
        }))
        present(vc, animated: true, completion: nil)
    }
    /// 显示h5的textInput弹窗
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        let vc = UIAlertController(title: prompt, message: "", preferredStyle: .alert)
        vc.addTextField { tf in
            tf.text = defaultText
        }
        vc.addAction(UIAlertAction(title: "完成", style: .default, handler: { _ in
            let tf = vc.textFields?.first
            completionHandler(tf?.text)
        }))
        present(vc, animated: true, completion: nil)
    }
}
